package com.yj.suncity.activity.shouye;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yj.suncity.R;
import com.yj.suncity.adapter.GoodsListAdapter;
import com.yj.suncity.adapter.GoodsListAdapter.ProductItemListener;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.async.ThreadUtils;
import com.yj.suncity.async.ThreadUtils.OnResultListener;
import com.yj.suncity.bean.AdvDetailBean;
import com.yj.suncity.bean.AdvGoodsBean;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.onekeyshare.ShowShare;
import com.yj.suncity.user.LoginActivity;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;

public class SeeAdvDetailActivity extends Activity implements OnClickListener{

	private Context context;
	private boolean isLogin;
	private boolean isShop;
	private String advId;
	private String adv_userId;
	private String userId = "";
	private ArrayList<String> arrayList;
	private int flag;// 1,首页->看广告列表->当前 2,分类信息/商品列表/超广广告->看广告列表->当前
	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();
	private AdvDetailBean advDetailBean;
	private ImageView mImg_logo;
	private TextView mTxt_shop_name, mTxt_shop_jianjie, mTxt_al_see_adv,
			mTxt_al_duihuan, mTxt_al_digou, mTxt_al_offer;// 详情顶部

	private TextView mTxt_contact_name, mTxt_contact_phone,
			mTxt_contact_address;// 联系

	private TextView mTxt_see_adv_jinbi, mTxt_share_adv_jinbi, mTxt_offer,
			mTxt_duihuan, mTxt_digou, mTxt_activity;// 详情下部
	
	private ListView mGoodsListView;
	private GoodsListAdapter mAdapter;
	
	private ViewPager pager;
	private LinearLayout lay_view_select;
	private ViewPagerScroll pagerScroll;
	private List<Object> listPaths = new ArrayList<Object>();

//	private HorizontalScrollView horizontalScrollView;
	private LinearLayout /*mLay_linear_goods,*/ mLay_linear_see_adv;
	private int mWidth;
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private String shopId;
	private ImageView mImag_collect_normal, mImag_collect_press;
	private boolean isCollect;
	private SoundPool pool;
	private boolean isSound;
	private ImageView mImageView_anim;
	private AnimationDrawable drawable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_adv_detail);
		context = this;
		advId = getIntent().getStringExtra("advid");
		adv_userId = getIntent().getStringExtra("adv_userid");
		flag = getIntent().getIntExtra("flag", -1);
		mWidth = getResources().getDisplayMetrics().widthPixels;
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				// .displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		isSound = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.SOUND, true);
		pool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5);
		pool.load(this, R.raw.bgm_coin_01, 1);
		findView();
		initData();
	}

	private void findView() {
		View view = LayoutInflater.from(context).inflate(R.layout.activity_adv_detail_head,
				null);
		mLay_linear_see_adv = (LinearLayout) findViewById(R.id.lay_linear_see_adv);
		if (flag == 2 && advId.equals("")) {
			mLay_linear_see_adv.setVisibility(View.GONE);
		}
		mImageView_anim = (ImageView) findViewById(R.id.img_anmiation);
		mImageView_anim.setVisibility(View.GONE);
		drawable = (AnimationDrawable) mImageView_anim.getBackground();
		isSound = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.SOUND, true);
//		findViewById(R.id.lay_rela_web_link).setOnClickListener(this);
//		findViewById(R.id.lay_linear_zhaiyao).setOnClickListener(this);
//		findViewById(R.id.lay_rela_see_adv).setOnClickListener(this);
//		findViewById(R.id.lay_rela_offer).setOnClickListener(this);
//		findViewById(R.id.lay_rela_duihuan).setOnClickListener(this);
//		findViewById(R.id.lay_rela_digou).setOnClickListener(this);
//		findViewById(R.id.lay_rela_huodong).setOnClickListener(this);
		
		lay_view_select = (LinearLayout) view.findViewById(R.id.lay_view_select);
		RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.lay_view_page);
		layout.setLayoutParams(new LinearLayout.LayoutParams(mWidth,
				(int) (mWidth / 2)));
		pager = (ViewPager) view.findViewById(R.id.view_pager);
		
		mImag_collect_normal = (ImageView) findViewById(R.id.img_collet_normal);
		mImag_collect_press = (ImageView) findViewById(R.id.img_collet_press);
//		mLay_linear_goods = (LinearLayout) view.findViewById(R.id.lay_linear_goods);
//		horizontalScrollView = (HorizontalScrollView) findViewById(R.id.lay_horizontal_ScrollView);
//
//		horizontalScrollView.setLayoutParams(new LinearLayout.LayoutParams(
//				mWidth, (mWidth - (Utils.dipTopx(context, 10))) / 4));

		mImg_logo = (ImageView) view.findViewById(R.id.img_logo);
		mTxt_shop_name = (TextView) view.findViewById(R.id.txt_shop_name);
		mTxt_shop_jianjie = (TextView) view.findViewById(R.id.txt_shop_jianjie);
		mTxt_al_see_adv = (TextView) view.findViewById(R.id.txt_al_see_adv);
		mTxt_al_duihuan = (TextView) view.findViewById(R.id.txt_al_duihuan);
		mTxt_al_digou = (TextView) view.findViewById(R.id.txt_al_digou);
		mTxt_al_offer = (TextView) view.findViewById(R.id.txt_al_offer);
		mGoodsListView = (ListView)findViewById(R.id.goods_list_view);
		

		mTxt_contact_name = (TextView) view.findViewById(R.id.txt_contact_name);
		mTxt_contact_phone = (TextView) view.findViewById(R.id.txt_contact_phone);
		mTxt_contact_address = (TextView) view.findViewById(R.id.txt_contact_address);
		mGoodsListView.addHeaderView(view);

//		mTxt_see_adv_jinbi = (TextView) findViewById(R.id.txt_see_adv_jinbi);
//		mTxt_share_adv_jinbi = (TextView) findViewById(R.id.txt_share_adv_jinbi);
//		mTxt_offer = (TextView) findViewById(R.id.txt_offer);
//		mTxt_duihuan = (TextView) findViewById(R.id.txt_duihuan);
//		mTxt_digou = (TextView) findViewById(R.id.txt_digou);
//		mTxt_activity = (TextView) findViewById(R.id.txt_huodong);

	}

	private void initData() {
		String path = URLCon.广告 + "?action=seeadvdetail&id=" + adv_userId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "正在加载......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						advDetailBean = new AdvDetailBean(jsonObject);
						shopId = advDetailBean.getUserid();
						
						if (advDetailBean.getImg().contains(",")) {
							String[] string = advDetailBean.getImg().split(
									",");
							for (String string2 : string) {
								listPaths.add(URLCon.HOST + string2);
							}
						} else {
							listPaths.add(URLCon.HOST+ advDetailBean.getImg());
						}
						pagerScroll = new ViewPagerScroll(context, pager,
								lay_view_select, listPaths);
//						int dip_5 = Utils.dipTopx(context, 5);
//						for (final AdvGoodsBean goodsBean : advDetailBean.getGoods()) {
//							ImageView imageView = new ImageView(context);
//							imageView.setTag(1);
//							imageView.setLayoutParams(new LayoutParams(
//									(mWidth - 2 * dip_5) / 4,
//									(mWidth - 2 * dip_5) / 4));
//							imageView.setScaleType(ScaleType.FIT_XY);
//							imageView.setPadding(dip_5, dip_5, dip_5, dip_5);
//							if (goodsBean.getImg_url().contains(",")) {
//								imageLoader.displayImage(
//										URLCon.HOST
//												+ (goodsBean.getImg_url()
//														.split(","))[0],
//										imageView, options);
//							} else {
//								imageLoader.displayImage(URLCon.HOST
//										+ goodsBean.getImg_url(), imageView,
//										options);
//							}
////							mLay_linear_goods.addView(imageView);
//							imageView.setOnClickListener(new OnClickListener() {
//								@Override
//								public void onClick(View v) {
//									Intent intent = new Intent(context,
//											ProductDateilsActivity.class);
//									intent.putExtra("goodid", goodsBean.getId());
////									intent.putExtra("flag", flag);
//									startActivity(intent);
//								}
//							});
//							
//						}
						WindowManager wm = getWindowManager();
						int scwidth = wm.getDefaultDisplay().getWidth();
						mAdapter = new GoodsListAdapter(SeeAdvDetailActivity.this, (ArrayList<AdvGoodsBean>)advDetailBean.getGoods(), scwidth, new ProductItemListener() {
							
							@Override
							public void productItemClick(int position) {
								// TODO Auto-generated method stub
								Intent intent = new Intent(context,
										ProductDateilsActivity.class);
								intent.putExtra("goodid", advDetailBean.getGoods().get(position).getId());
								intent.putExtra("flag", flag);
								startActivity(intent);
							}
						});
						mGoodsListView.setAdapter(mAdapter);
//						setListViewHeightBasedOnChildren(mGoodsListView);
							
						
						setValue();
					}
				});
		asyncTaskUtil.execute(path);
	}
	private void setListViewHeightBasedOnChildren(ListView listView) {

		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}
	@Override
	protected void onResume() {
		isLogin = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.ISLOGIN, false);
		isShop = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.USERTYPE, false);
		if (isLogin) {
			userId = preferencesUtil.getString(context, ShareCon.USERFILE,
					ShareCon.USERID, "");
			getCollectStatus();
		}
		if (pagerScroll != null) {
			pagerScroll.startTimer();
		}
		super.onResume();
	}
	@Override
	protected void onPause() {
		if (pagerScroll != null) {
			pagerScroll.stopTimer();
		}
		super.onPause();
	}
	private void setValue() {

		imageLoader.displayImage(URLCon.HOST + advDetailBean.getEnt_logo(),
				mImg_logo, options);
		mTxt_shop_name.setText(advDetailBean.getEntname());
		mTxt_shop_jianjie.setText(advDetailBean.getEnt_jianjie());
		mTxt_al_see_adv.setText(advDetailBean.getSee_num());
		mTxt_al_duihuan.setText(advDetailBean.getDhsy_num());
		mTxt_al_digou.setText(advDetailBean.getDg_num());
		mTxt_al_offer.setText(advDetailBean.getShare_num());

		mTxt_contact_name.setText(advDetailBean.getEnt_contact());
		mTxt_contact_phone.setText(advDetailBean.getEnt_contact_tel());
		mTxt_contact_address.setText(advDetailBean.getEnt_address());
		mTxt_contact_phone.setOnClickListener(new OnClickListener() {// 拨打电话
					@Override
					public void onClick(View v) {
						DialogUtils dialogUtils = DialogUtils.getInstance();
						dialogUtils.CallDialog(context,
								advDetailBean.getEnt_contact_tel());
					}
				});

//		mTxt_see_adv_jinbi.setText(advDetailBean.getGive_num());
//		mTxt_share_adv_jinbi.setText(advDetailBean.getSharegivenum());
//		mTxt_offer.setText(advDetailBean.getOffer_give_num());
//		mTxt_duihuan.setText(advDetailBean.getDhgoodssurplus());
//		mTxt_digou.setText(advDetailBean.getDggoodssurplus());
//		mTxt_activity.setText(advDetailBean.getActivitynum());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.btn_see_adv:// 看广告
			if (!isLogin) {
				startActivity(new Intent(this, LoginActivity.class));
				return;
			}
			seeAdv("seeadv");
			break;
		case R.id.btn_share_adv:// 分享广告
			if (!isLogin) {
				startActivity(new Intent(this, LoginActivity.class));
				return;
			}
			shareAdv("shareadv");
			break;
		case R.id.lay_linear_zhaiyao:// 摘要
			Intent intshop = new Intent(this, ShopGoodsListActivity.class);
			intshop.putExtra("titlename", "全部商品");
			intshop.putExtra("userid", shopId);
			startActivity(intshop);
			break;
//		case R.id.lay_rela_see_adv:// 看广告
			// if(shopId!=null){
			// Intent it1=new Intent(this, SeeAdvListActivity.class);
			// it1.putExtra("userid", shopId);
			// startActivity(it1);
			// }
//			break;
//		case R.id.lay_rela_offer:// 接悬赏
//			if (shopId != null) {
//				Intent it1 = new Intent(this, OfferListActivity.class);
//				it1.putExtra("userid", shopId);
//				startActivity(it1);
//			}
//			break;
//		case R.id.lay_rela_duihuan:// 兑换
//			if (shopId != null) {
//				Intent it1 = new Intent(this, DuihuanShopListActivity.class);
//				it1.putExtra("userid", shopId);
//				startActivity(it1);
//			}
//			break;
//		case R.id.lay_rela_digou:// 抵购
//			if (shopId != null) {
//				Intent it1 = new Intent(this, DigouShopListActivity.class);
//				it1.putExtra("userid", shopId);
//				startActivity(it1);
//			}
//			break;
//		case R.id.lay_rela_huodong:// 活动
//			if (shopId != null) {
//				Intent it1 = new Intent(this, RecentHuodongActivity.class);
//				it1.putExtra("userid", shopId);
//				startActivity(it1);
//			}
//			break;
//		case R.id.lay_rela_web_link:// 一键链接
//			if (!advDetailBean.getEnt_weblink().equals("")) {
//				Intent intent = new Intent(Intent.ACTION_VIEW);
//				if (advDetailBean.getEnt_weblink().contains("http://")) {
//					intent.setData(Uri.parse(advDetailBean.getEnt_weblink()));
//				}else{
//					intent.setData(Uri.parse("http://"+advDetailBean.getEnt_weblink()));
//				}
//				startActivity(intent);
//			}else{
//				ToastUtil.ShowToast(context, "该商家暂时没有上传网站！");
//			}
//			break;
		case R.id.lay_rela_collect:// 添加/移除收藏
			if (shopId != null) {
				if (!isLogin) {
					startActivity(new Intent(this, LoginActivity.class));
					return;
				}
				if (isCollect) {
					removeCollect();
				} else {
					addCollect();
				}
			}
			break;
		}
	}

	private void addCollect() {
		String path;
		if (flag == 2) {
			path = URLCon.收藏 + "?action=addcollection&userid=" + userId
					+ "&id=" + adv_userId + "&type=1";
		} else {
			path = URLCon.收藏 + "?action=addcollection&userid=" + userId
					+ "&id=" + advId + "&type=2";
		}
		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "添加收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = true;
							mImag_collect_normal.setVisibility(View.GONE);
							mImag_collect_press.setVisibility(View.VISIBLE);
							ToastUtil.ShowToast(context, "收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void getCollectStatus() {
		String path;
		if (flag == 2) {
			path = URLCon.收藏 + "?action=getcollectionstate&userid=" + userId
					+ "&id=" + adv_userId + "&type=1";
		} else {
			path = URLCon.收藏 + "?action=getcollectionstate&userid=" + userId
					+ "&id=" + advId + "&type=2";
		}
		Log.d("", "获取收藏：" + path);
		ThreadUtils threadUtils = new ThreadUtils();
		threadUtils.startThread(path, new OnResultListener() {
			@Override
			public void jsonResult(JSONObject json) {
				if (json.optString("success").equals("1")) {
					if (json.optString("state").equals("1")) {
						isCollect = true;
						mImag_collect_normal.setVisibility(View.GONE);
						mImag_collect_press.setVisibility(View.VISIBLE);
					} else {
						isCollect = false;
						mImag_collect_normal.setVisibility(View.VISIBLE);
						mImag_collect_press.setVisibility(View.GONE);
					}
				}
			}
		});
	}

	private void removeCollect() {
		String path;
		if (flag == 2) {
			path = URLCon.收藏 + "?action=delcollection&userid=" + userId
					+ "&id=" + adv_userId + "&type=1";
		} else {
			path = URLCon.收藏 + "?action=delcollection&userid=" + userId
					+ "&id=" + advId + "&type=2";
		}
		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "删除收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = false;
							setResult(1);// 如果收藏删除成功返回得重新加载
							mImag_collect_normal.setVisibility(View.VISIBLE);
							mImag_collect_press.setVisibility(View.GONE);
							ToastUtil.ShowToast(context, "删除收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void seeAdv(final String type) {
		String path;
		if (flag == 2) {
			path = URLCon.广告 + "?action="+type+"&userid=" + userId + "&id="
					+ advId + "&type=1";
		} else {
			path = URLCon.广告 + "?action="+type+"&userid=" + userId + "&id="
					+ advId + "&type=2";
		}
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						DialogUtils dialogUtils = DialogUtils.getInstance();
						
						if (jsonObject.optString("success").equals("1")) {
							if(type.equals("shareadv")){
								Intent intent = new Intent();
								intent.setClass(SeeAdvDetailActivity.this, HongbaoDialog.class);
								JSONObject data = jsonObject.optJSONObject("data");
								if (data != null) {
									intent.putExtra("share_typename", data.optString("share_typename"));
									intent.putExtra("hongbao", data.optString("share_content"));
									intent.putExtra("id", data.optString("id"));
								}
								startActivity(intent);
							}else{								
								soundAima(jsonObject.optString("amount"));
							}
							
						}else{
							dialogUtils.backDialog(context,
									jsonObject.optString("msg"), false, null);
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void shareAdv(String type) {
//		Intent intent = new Intent();
//		intent.setClass(SeeAdvDetailActivity.this, HongbaoDialog.class);
//		intent.putExtra("hongbao", "恭喜您，得到了优惠券");
//		startActivity(intent);
//		seeAdv("shareadv");
		ShowShare share = new ShowShare(context,null, new OneKeyShareCallback());
		share.showShare(
				advDetailBean.getEntname(),
				advDetailBean.getEnt_jianjie(),
				URLCon.HOST+"/web/index.html",
				URLCon.HOST + advDetailBean.getEnt_logo());
	}

	public class OneKeyShareCallback implements PlatformActionListener {

		public void onComplete(Platform plat, int action,
				HashMap<String, Object> res) {
			Log.d(getClass().getSimpleName(), res.toString());
			// 在这里添加分享成功的处理代码
			if (res.toString()!=null&&!res.toString().equals("")) {
				seeAdv("shareadv");
			}
		}

		public void onError(Platform plat, int action, Throwable t) {
			t.printStackTrace();
			// 在这里添加分享失败的处理代码
			ToastUtil.ShowToast(context, "分享失败！");
		}

		public void onCancel(Platform plat, int action) {
			// 在这里添加取消分享的处理代码
			ToastUtil.ShowToast(context, "您已取消分享！");
		}
	}
	
	private void soundAima(String number){
		if (isSound) {
			pool.play(1, 1, 1, 0, 0, 1);
		}
		mImageView_anim.setVisibility(View.VISIBLE);
		if (drawable.isRunning()) {
			drawable.stop();
			drawable.start();
		}else{
			drawable.start();
		}
		ToastUtil.ShowToast(getApplicationContext(), "恭喜您，得到了"+number+"元现金");
		
	}
}
